package com.fa4j.product.category.controller;


import com.fa4j.common.base.exception.CommonRequestError;
import com.fa4j.common.base.model.CommonConstants;
import com.fa4j.common.base.model.RemoveCmd;
import com.fa4j.common.base.util.TreeUtil;
import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.model.AppType;
import com.fa4j.product.category.model.Category;
import com.fa4j.product.category.model.CategoryCreateCmd;
import com.fa4j.product.category.model.CategoryModifyCmd;
import com.fa4j.product.category.repository.CategoryRepository;
import com.fa4j.product.category.service.CategoryService;
import com.fa4j.system.file.service.FileUrlFillService;
import com.fa4j.system.login.util.LoginUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Web接口-商品分类
 *
 * @since 2025-11-22 21:06:24
 */
@RestController
@RequestMapping("product/category")
@RequiredArgsConstructor
public class CategoryController {

    private final CategoryService categoryService;
    private final FileUrlFillService fileUrlFillService;
    private final CategoryRepository categoryRepository;

    @GetMapping("tree")
    @ApiMethod(name = "商品分类-树查询", type = AppType.MANAGE)
    public List<Category> queryTree() {
        List<Category> list = categoryRepository.queryAllList();
        fileUrlFillService.fill(list, Category::getImgId, Category::setImgUrl);
        return TreeUtil.listToTree(list, CommonConstants.TREE_ROOT_ID);
    }

    @PostMapping
    @ApiMethod(name = "商品分类-创建", type = AppType.MANAGE)
    public Category create(@Valid @RequestBody CategoryCreateCmd cmd) {
        return categoryService.create(cmd);
    }

    @PatchMapping
    @ApiMethod(name = "商品分类-编辑", type = AppType.MANAGE)
    public Category modify(@Valid @RequestBody CategoryModifyCmd cmd) {
        return categoryService.modify(cmd);
    }

    @DeleteMapping("{id}")
    @ApiMethod(name = "商品分类-删除", type = AppType.MANAGE)
    public Category remove(@PathVariable Integer id) {
        return categoryService.remove(RemoveCmd.of(id, LoginUtil.getAccountId()));
    }

    @GetMapping("{id}")
    @ApiMethod(name = "商品分类-详情查询", type = AppType.MANAGE)
    public Category detail(@PathVariable Integer id) {
        return categoryRepository.findById(id)
                .orElseThrow(() -> CommonRequestError.NOT_FOUND.build("商品分类"));
    }
}

